<?php

// +----------------------------------------------------------------------
// | 用户管理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\ucenter\admin;

use app\controller\admin\Common;
use app\common\middleware\UserAuth;
use app\controller\pay\admin\MoneyLog;
use app\controller\pos\admin\Pos;
use app\model\ucenter\MemberInfo;
use app\model\ucenter\User as UserModel;
use app\event\ucenter\User as UserEvent;
use app\event\ucenter\Sms as SmsEvent;
use app\event\ucenter\Email as EmailEvent;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\ucenter\UserCash as UserCashModel;
use think\facade\Session;
use yicmf\builder\Edit;
use yicmf\builder\Table;
use think\facade\Url;

class User extends Common
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new UserModel();
    }


    public function index()
    {
        $map[] = ['status', '>', -2];
        // 黑名单
        $builder = new Table();
        $builder->model(UserModel::class)
            ->excel()
            ->where($map)
//				->excel()
//				->excel(function ($data)
//				{
//					dump($data);
//				})
            ->order('id DESC')
            //                ->suggest('管理用户信息')
            ->searchText('id', '用户ID')
            ->searchText('agent_id', '服务商ID')
            ->searchTextLike('nickname', '用户昵称')
            ->searchText('mobile', '手机号')
            ->searchDateTimeRange('create_time','注册时间')
            ->searchDateTimeRange('logintime','最后登录')
//				->buttonUpdate('ucenter/admin/User/update', '新增')
            ->keyId()
//                ->keyText('account', '用户账号')
            ->keyText('username', '用户名')
            ->keyText('nickname', '昵称')
//            ->keyText('mobile', '手机')
            ->keyClosure('推广码', function ($data) {
                return 'F' . $data['shareCode'];
            })
            ->keyClosure('POS等级', function ($data) {
                return 'V' . $data['pos_level'];
            })
            ->keyClosure('平台等级', function ($data) {
                $vip_names = ['新手入门', '初级合伙人', '中级合伙人', '高级合伙人'];
                return $vip_names[$data['level']];
            })
//            ->keyText('level', '等级')
            ->keyText('money', '余额')
//                ->keyText('my_balance', '专享资金')
            ->keyText('pid', '上级')
            ->keyClosure('上级昵称', function ($data) {
                return UserModel::where('id', $data['pid'])->value('nickname');
            })
            ->keyText('bid', '推荐人')
            ->keyTime('last_login_time', '最后登录')
//            ->keyClosure('最后登录', function ($data) {
//                return time_format($data['logintime']);
//            })
//				->keyUser('invite_id', '邀请人')
//            ->keyTime('logintime', '最后登录')
            ->keyTime('create_time', '注册时间')
            ->keyStatus()
            ->actionUpdate('agent?id={$id}', '代理')
            ->actionUpdate()
            ->totalRowField('id','总计：')
            ->totalRowField('money','{{= (d.TOTAL_NUMS) }}元')
//				->actionUpdate('pwd?id={$id}', '密码', [], true)
            //             ->actionUpdate('ucenter/admin/AuthGroup/group?id={$id}', '授权')
            ->actionRestore()
            ->actionView()
            ->actionForbid()//				->actionDelete()
        ;
        return $builder->fetch();
    }

    public function blacklist()
    {
        $map[] = ['status', '=', -1];
        // 黑名单
        $builder = new Table();
        $builder->model(UserModel::class)
            ->where($map)
            ->order('id DESC')
            ->searchTextLike('nickname', '用户昵称')
            ->searchText('mobile', '手机号')
            ->keyId()
            ->keyText('email', '邮箱')
            ->keyText('mobile', '手机')
            ->keyText('nickname', '用户昵称')
            ->keyText('balance', '余额')
            ->keyTime('last_login_time', '最近登陆')
            ->keyStatus()
            ->actionRestore();
        return $builder->fetch();
    }

    public function info()
    {
        return $this->fetch();
    }
    public function home()
    {
        $info['today']['new'] = UserModel::where('create_time','today')->count();
        $info['today']['task'] = UserMoneyLogModel::where('create_time','today')->distinct(true)->field('user_id')->count();
        $info['today']['pid'] = UserModel::where('create_time','today')->distinct(true)->field('pid')->count();
        $info['today']['cash'] = UserCashModel::where('create_time','today')->distinct(true)->field('user_id')->count();
        $info['today']['active'] = UserModel::where('active_time','today')->count();
        $info['yesterday']['new'] = UserModel::where('create_time','yesterday')->count();
        $info['yesterday']['pid'] = UserModel::where('create_time','yesterday')->distinct(true)->field('pid')->count();
        $info['yesterday']['task'] = UserMoneyLogModel::where('create_time','yesterday')->distinct(true)->field('user_id')->count();
        $info['yesterday']['cash'] = UserCashModel::where('create_time','yesterday')->distinct(true)->field('user_id')->count();
        $info['yesterday']['active'] = UserModel::where('active_time','yesterday')->count();
        $this->assign('info',$info);
        return $this->fetch();
    }

    public function tj()
    {
        $data['code'] = 0;
        $data['data']['task7']['no'] = 2;
        $data['data']['task7']['do'] = 6;

        $register_user = UserModel::where('status', 1)
            ->field('DATE_FORMAT(create_time,"%Y%m%d") days,count(id) num')->whereTime('create_time',  ' -31 day')->group('days')->select();
        $register_real = UserModel::where('status', 1)
            ->field('DATE_FORMAT(create_time,"%Y%m%d") days,count(id) num')->where('realName',1)->whereTime('create_time',  ' -31 day')->group('days')->select();

        $register['tooltip'] = ['trigger' => 'axis'];
        $register['calculable'] = true;
        $register['legend'] = ['data' => ['新增注册','新增实名']];

        $register['toolbox'] = ['show' => true, 'feature' => [
            'restore' => [
                'show' => true
            ],
            'mark' => [
                'show' => false
            ],
            'saveAsImage' => [
                'show' => true
            ],
        ]];
        $x = [];
        $series = [];
        for ($i = 31; $i >= 0; $i--) {
            $day = date('Ymd', strtotime( ' -' . $i . '  day'));
            $num = 0;
            $x[] = $day;
            foreach ($register_user as $item) {
                if ($item['days'] == $day) {
                    $num = $item['num'];
                    break;
                }
            }
            $series[] = $num;
        }
        $x = [];
        $serie2 = [];
        for ($i = 31; $i >= 0; $i--) {
            $day = date('Ymd', strtotime( ' -' . $i . '  day'));
            $num = 0;
            $x[] = $day;
            foreach ($register_real as $item) {
                if ($item['days'] == $day) {
                    $num = $item['num'];
                    break;
                }
            }
            $serie2[] = $num;
        }
        $register['xAxis'] = ['type' => 'category', 'data' => $x];
        $register['yAxis'] = ['type' => 'value'];
        $register['series'] = [
            ['name' => '新增注册', 'type' => 'line','data' => $series],
            ['name' => '新增实名', 'type' => 'line', 'data' => $serie2]
        ];
        $data['data']['register'] = $register;
        $data['data']['users'] = ['1','2'];

        return $this->json($data);
    }
    public function view()
    {
        $user = UserModel::where('id',$this->request->param('id'))->find();
        if ($user)
        {
            $this->assign('member_level_list',MemberInfo::select());
            $this->assign('data',$user);

            $men = new MoneyLog();
            $this->assign('money_log',$men->userHtml());
            $pos = new Pos();
            $this->assign('pos_log',$pos->userHtml());
            return $this->fetch();
        }else{
            $this->error('信息不存在');
        }

    }

    public function pwd()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['password'] = $param['new_password'];
            $param['password_confirm'] = $param['password'];

            $event = new UserEvent();
            $result = $event->adminChangePassword($param, $this->user);
            if (0 == $result['code']) {
                $this->_returnSuccess($result['message']);
            } else {
                $this->_returnError($result['message']);
            }
        } else {
            $id = $this->request->get('id', 0);
            if ($id) {
                $data = UserModel::where('id', $id)->find();
                if (!$data) {
                    $this->_returnError('用户信息不存在');
                }
                // 查询权限组
                $role = $data->roles()->find();
                if ($role) {
                    $data['auth_group_ids'] = $role['id'];
                } else {
                    $data['auth_group_ids'] = 101;
                }
            } else {
                $data = [];
//					$data['is_vip'] = 0;
                $data['password'] = '000000';
            }
            $builder = new Edit();
            $builder->title('修改密码');
            $builder->keyHidden('id');
            $builder->keyPassword('new_password', '新密码', '密码至少要求6个字符')
                ->data($data)
                ->buttonSubmit();
            return $builder->fetch();
        }
    }

    public function update()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
//				if (!$param['id']) {
//					$param['password_confirm'] = $param['password'];
//					$result = $this->validate($param, '\app\validate\ucenter\User.register');
//				} else {
//					$result = $this->validate($param, '\app\validate\ucenter\User.update');
//				}
//				if ($result !== true) {
//					$this->_returnError('用户数据验证失败：' . $result);
//				}
            $event = new UserEvent();
            $result = $event->updateByAdmin($param, $this->user);
            if (0 == $result['code']) {
                $this->_returnSuccess($result['message']);
            } else {
                $this->_returnError($result['message']);
            }
        } else {
            $id = $this->request->get('id', 0);
            if ($id) {
                $data = UserModel::where('id', $id)->find();
                if (!$data) {
                    $this->_returnError('用户信息不存在');
                }
                // 查询权限组
//					$role = $data->roles()->find();
//					if ($role) {
//						$data['auth_group_ids'] = $role['id'];
//					} else {
//						$data['auth_group_ids'] = 101;
//					}
            } else {
                $this->_returnError('用户信息不存在');
            }
            $data = $data->getData();
//				$grade = \app\model\ucenter\UserGrade::where('status', 1)->column('name', 'id');
//				$data['order'] = $data->orders()->where('status', '>', -2)->count();
            $builder = new Edit();
            $builder->title('用户详情');

            $builder
                ->keyReadOnly('username', '用户名', '不可编辑')
                ->keyTextInline('nickname', '昵称', '可重复')
                ->keyImage('avatar', '头像')
                ->keyPassword('new_password', '新密码', '不填写不修改')
                ->keyMobile('mobile', '手机')
                ->keyTextInline('idCardName', '提款姓名', '（支付宝）')
                ->keyTextInline('alipay_no', '提款账号', '（支付宝）')
                ->keyTextInline('wechat', '微信号')
                ->keyTextInline('level', '等级')
//					->keySelect('user_grade_id', '会员等级', $grade)
                ->keySex()
//					->keyDate('birthday', '生日')
//					->keyText('qq', 'qq')
//					->keyLabel('create_time', '注册时间')
//					->keyLabel('last_login_time', '最后登录')
//					->keyLabel('point', '积分',)
//					->keyLabel('balance', '余额', '更多<a style="cursor:pointer " lay-href="' . url('pay/admin/UserBalance/index?user_id=' . $data['id']) . '" >详情点这里</a>')
//					->keyLabel('order', '订单数', '更多<a style="cursor:pointer " lay-href="' . url('merchant/Order/index?user_id=' . $data['id']) . '" >详情点这里</a>')
//					->keyHtml('add',$html,'标题')
//                    ->keyText('website', '站点')
//                    ->keyTextArea('introduction', '个性签名')
//                    ->keyBool('is_vip', '是否金牌卖家')

//					->group('基本信息', 'account,nickname,avatar_id,email,mobile,user_grade_id,sex,birthday')
//					->group('账户信息', 'create_time,last_login_time,point,balance,order')
//					->group('地址', 'add')
                ->data($data);
//				if (UserEvent::isAdministrator($this->user)) {
            $builder->buttonSubmit();
//				}
            return $builder->fetch();
        }
    }

    public function agent()
    {
        if ($this->request->isPost()) {

            $user = UserModel::where('id', $this->request->param('id'))->find();
            if (!$user) {
                $this->_returnError('用户不存在');
            }

            $user['agent_id'] = $user['id'];
            $user['is_agency'] = $this->request->param('is_agency');
            $user['deposit_agent'] = $this->request->param('deposit_agent');
            $user['idCardName'] = $this->request->param('idCardName');
            $user['idCard'] = $this->request->param('idCard');
            $user['realName'] = 1;
            $user['nickname'] = $user['idCardName'];
            if ($user['is_agency'] == 1) {
                $user['agency_time'] = time_format();
            } else {
                $user['agency_time'] = null;
            }
            if ($user->save()) {
                $this->_returnSuccess('保存成功');
            } else {
                $this->_returnError('保存失败');
            }

        } else {
            $id = $this->request->get('id', 0);
            if ($id) {
                $data = UserModel::where('id', $id)->find();
                if (!$data) {
                    $this->_returnError('用户信息不存在');
                }
            } else {
                $this->_returnError('用户信息不存在');
            }
            $data = $data->getData();
            $builder = new Edit();
            $builder->title('代理管理');

            $builder
                ->keyReadOnly('username', '用户名', '不可编辑')
                ->keyTextInline('nickname', '昵称', '可重复')
                ->keyTextInline('idCardName', '身份证姓名', '')
                ->keyTextInline('idCard', '身份证号码', '')
                ->keyBool('is_agency', '是否代理')
                ->keyDecimal('deposit_agent', '代理保证金')
                ->data($data);
//				if (UserEvent::isAdministrator($this->user)) {
            $builder->buttonSubmit();
//				}
            return $builder->fetch();
        }
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (!$param['id']) {
                $param['password_confirm'] = $param['password'];
                $result = $this->validate($param, 'User.register');
            } else {
                $result = $this->validate($param, 'User.update');
            }
            if ($result !== true) {
                $this->_returnError('用户数据验证失败：' . $result);
            }
            $event = new UserEvent();
            $result = $event->updateByAdmin($param, $this->user);
            if (0 == $result['code']) {
                $this->_returnSuccess($result['message']);
            } else {
                $this->_returnError($result['message']);
            }
        } else {
            $id = $this->request->get('id', 0);
            if ($id) {
                $data = UserModel::where('id', $id)->find();
                if (!$data) {
                    $this->_returnError('用户信息不存在');
                }
                // 查询权限组
                $role = $data->roles()->find();
                if ($role) {
                    $data['auth_group_ids'] = $role['id'];
                } else {
                    $data['auth_group_ids'] = 101;
                }
            } else {
                $data = [];
//					$data['is_vip'] = 0;
                $data['password'] = '000000';
            }

            $grade = \app\model\ucenter\UserGrade::where('status', 1)->column('name', 'id');

            $builder = new Edit();
            $builder->title($id ? '编辑用户' : '新增用户');

            $builder->keyReadOnly('account', '用户名', '不可编辑')
                ->keyTextInline('nickname', '昵称', '可重复')
                ->keyImageModel('avatar_id', '头像')
                ->keyTextInline('email', '邮箱')
                ->keyMobile('mobile', '手机')
                ->keySelect('user_grade_id', '会员等级', $grade)
                ->keySex()
                ->keyDate('birthday', '生日')
//                    ->keyText('qq', 'qq')
//                    ->keyText('wechat', '微信')
//                    ->keyText('website', '站点')
//                    ->keyTextArea('introduction', '个性签名')
//                    ->keyBool('is_vip', '是否金牌卖家')
                ->data($data)
                ->buttonSubmit();
            return $builder->fetch();
        }
    }

    public function find()
    {
        if ($this->request->isPost()) {
            $user = $this->model->where('id|account', $this->request->post('account'))->find();
            if ($user) {
                $data['code'] = 0;
                $data['data'] = $user;
            } else {
                $data['code'] = 1;
                $data['message'] = '暂无';
            }
            return json($data);
        } else {
            $this->assign('users', $this->model->all());
            $this->assign('value', $this->request->get('value', ''));
            $this->assign('callback', $this->request->get('callback'));
            return $this->fetch();
        }
    }

    public function forbid()
    {
        $course = UserModel::where('id', $this->request->param('id'))->find();
        if ($course) {
            $course['status'] = -1;
            if ($course->save()) {
                $this->_returnSuccess('禁用成功');;
            } else {
                $this->_returnError('禁用失败');
            }
        } else {
            $this->_returnError('操作异常');
        }
    }

    public function restore()
    {
        $course = UserModel::where('id', $this->request->param('id'))->find();
        if ($course) {
            $course['status'] = 1;
            if ($course->save()) {
                $this->_returnSuccess('还原成功');;
            } else {
                $this->_returnError('还原失败');
            }
        } else {
            $this->_returnError('操作异常');
        }
    }


    /**
     * 修改密码
     * @return mixed
     * @throws \Exception
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function password()
    {
        if ($this->request->isPost()) {
//				if (false === UserEvent::checkPassword($this->request->post('old_password'), $this->user)) {
//					$this->_returnError('旧密码验证失败');
//				} else {
//					$result = $this->validate($this->request->post(), 'User.changepassword');
//					if (true !== $result) {
//						$this->_returnError($result);
//					} else {
            $event = new UserEvent();
            $result = $event->updatePassword($this->request->post(), $this->user);
            if (0 === $result['code']) {
                $this->_returnSuccess('密码修改成功！', true);
            } else {
                $this->_returnError('修改失败，错误信息：' . $result['message']);
            }
//					}
//				}
        } else {
            $builder = new Edit();
            $builder->title('修改密码')
//					->keySafeCheck('mobile,email', '安全检测')
                ->keyPassword('old_password', '旧密码')
                ->keyPassword('password_confirm', '新密码')
                ->keyPassword('password', '确认新密码')
//					->data($this->user)
                ->buttonSubmit('password', '提交修改');
            return $builder->fetch();
        }
    }

    /**
     * 修改资料
     * @return string
     * @throws \Exception
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function profile()
    {
        if ($this->request->isPost()) {
            $result = $this->validate($this->request->post(), 'app\validate\ucenter\User.profile');
            if (true === $result) {
                $user = new UserEvent();
                $data = $user->profile($this->request->param(), $this->user);
                if (0 == $data['code']) {
                    $this->_returnSuccess('资料修改成功！', true);
                } else {
                    $this->_returnError('资料失败，错误信息：' . $data['message']);
                }
            } else {
                $this->_returnError('修改失败，错误信息：' . $result);
            }
        } else {
            $builder = new Edit();
            $builder->title('编辑资料')
//					->keySafeCheck('mobile,email', '安全检测')
                ->keyTextInline('account', '登录名', '不可修改');
//				if (1 == $this->user['is_auth']) {
//					$builder->keyLabel('auth_name', '认证名', '不可修改');
//				}
            $builder->keyTextInline('nickname', '昵称')
                ->keyTextInline('mobile', '手机')
                ->keyEmail('email', '邮箱')
                ->keySex('sex')
                ->keyImageModel('avatar_id', '头像', null, null, 2)
                //                    ->keyTextArea('introduction', '个性签名')
                ->data($this->user)
                ->buttonSubmit('', '保存');
            return $builder->fetch();
        }
    }

    /**
     * 更新在线时长
     * @return \think\response\Json
     * @throws \Exception
     * @author  : 微尘 <yicmf@qq.com>
     */
    public function online()
    {

        if (!Session::has('last_active_time') || Session::get('last_active_time') !== time()) {
            Session::set('last_active_time', time());
            // 控制在线时长
            $online = $this->user->onlines()->whereTime('end_time', '>', '-2 minutes')->order('id DESC')->where('ip', $this->request->ip())->find();
            if ($online) {
                $this->user['online_time'] = $this->user['online_time'] + time() - strtotime($online['end_time']);
                $this->user['last_active_time'] = time_format();
                $this->user->save();
                $online['duration'] = $online['duration'] + time() - strtotime($online['end_time']);
                $online['end_time'] = $this->user['last_active_time'];
            } else {
                // 新增记录
                $online = [];
                $online['duration'] = 1;
                $online['start_time'] = time_format();
                $online['end_time'] = time_format(time() + 1);
                $this->user->onlines()->save($online);
                $this->user['online_time'] = $this->user['online_time'] + 1;
                $this->user['last_active_time'] = $online['end_time'];
            }
            $this->user->isAutoWriteTimestamp(false)->save();
            $data['data']['online_time'] = $this->user['online_time'];

        }
        $data['data']['notice'] = $this->user->messages()->where('is_read', 0)->where('status', 1)->count('*');;
        $data['code'] = 0;
        return json($data);
    }

    public function statistics()
    {
        $result = $this->model->where('status', 1)
            ->field('DATE_FORMAT(create_time,"%Y%m") days,count(id) num')->whereTime('create_time', date('Y-m-01') . ' -6 month')->group('days')->select();
        //            $chart = new Chart();
        $data = [];
        $data['tooltip'] = ['trigger' => 'axis'];
        $data['legend'] = ['data' => ['注册量']];
        $data['toolbox'] = ['show' => true, 'feature' => [
            'restore' => [
                'show' => true
            ],
            'mark' => [
                'show' => false
            ],
            'saveAsImage' => [
                'show' => true
            ],
        ]];
        $x = [];
        $series = [];
        for ($i = 6; $i >= 0; $i--) {
            $day = date('Ym', strtotime(date('Y-m-01') . ' -' . $i . '  month'));
            $num = 0;
            $x[] = $day;
            foreach ($result as $item) {
                if ($item['days'] == $day) {
                    $num = $item['num'];
                    break;
                }
            }
            $series[] = $num;
        }
        $data['xAxis'] = ['type' => 'category', 'data' => $x];
        $data['yAxis'] = ['type' => 'value'];
        $data['series'] = [
            ['name' => '注册量', 'type' => 'line', 'data' => $series]
        ];
        return json($data);
    }

    public function outxls()
    {
//			$map = $this->_search();
//			if (method_exists($this, '_filter')) {
//				$this->_filter($map);
//			}
        $list = $this->model
//				->order($this->request->get('orderField') . ' ' . $this->request->get('orderDirection'))
            ->limit(2000)
            ->field('id,nickname,auth_name,mobile,is_vip,income_balance,create_time')
            ->select();
        $headArr = [
            'ID',
            '昵称',
            '真实姓名',
            '手机号',
            '认证讲师',
            '累积收益',
            '注册时间'
        ];
        $filename = '用户导出';
        $this->excelOut($filename, $headArr, $list);
    }

    public function outxls_check()
    {
        $list = $this->model->where('id', 'in', $this->request->param('expids'))
            ->field('id,nickname,auth_name,mobile,is_vip,good_at,income_balance,create_time')
            ->select();
        $headArr = [
            'ID',
            '昵称',
            '真实姓名',
            '手机号',
            '认证讲师',
            '擅长',
            '累积收益',
            '注册时间'
        ];
        $filename = '用户导出';
        $this->excelOut($filename, $headArr, $list);
    }
}
